package com.edu.netty.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * <p>
 * netty服务端
 * </p>
 *
 * @author jpge
 * @since 2024-03-29
 */
public class Server {

    private final int port;

    public Server(int port) {
        this.port = port;
    }

    public void run() throws Exception {

        // 1. netty辅助启动类
        ServerBootstrap bootstrap = new ServerBootstrap();

        // 2. 定义线程池
        // 线程池,用来处理接收连接请求的线程池
        EventLoopGroup boss = new NioEventLoopGroup();
        // 线程池,用来处理具体的工作
        EventLoopGroup worker = new NioEventLoopGroup();

        // 3. 设置引导类的属性
        bootstrap.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        // 注册自定义处理程序, 启动类引导程序与具体处理类关联
                        socketChannel.pipeline().addLast(new ServerHandler());
                    }
                })
                // 启动类队列长度
                .option(ChannelOption.SO_BACKLOG, 128)
                // 保持长连接
                .childOption(ChannelOption.SO_KEEPALIVE, true);

        // 4. 绑定端口
        try {
            ChannelFuture channelFuture = bootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }

    }

    public static void main(String[] args) throws Exception {
        new Server(10010).run();
    }

}
